/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wave;

import ast.*;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Vector;
import base.*;
import trackmsg.EchoMsg;
import trackmsg.TrackCtrlMsg;

/**
 *
 * @author Quest
 */
//TODO Hieu Black did not check NONE, example: 0 ==; == NONE; 0 >= NONE;....
public class ASTGreaterEqualExecution extends WaveExecution {

    public ASTGreaterEqualExecution(WaveHeadParser parser, WaveEnvironment waveEnv) {
        super(parser, waveEnv);
    }

    public void execute(ASTGreaterEqual grEquals, String tail) {
        Utilities.WPPrint("Execute Greater Equal");
        Vector vLeft = getLeftChild(grEquals);
        Vector vRight = getRightChild(grEquals);
        boolean result = false;
        if (vLeft.size() > 0 && vRight.size() > 0) {
            result = WaveActs.lessEqual(vRight, vLeft);
        }
        if (waveEnv.getTrackAddress() != null) {
            TrackNode fromTrack = wi.getTrackForest().getTrackNode(waveEnv.getTrackAddress());
            TrackNode.Echo echo = result ? echo = TrackNode.Echo.TRUE : TrackNode.Echo.FALSE;
            if (tail.equals("")) {
                TrackCtrlMsg msg = new EchoMsg(fromTrack, echo, waveEnv);
                wi.getTrackQueue().incoming(msg);
            } else if (result == false) {
                TrackCtrlMsg msg = new EchoMsg(fromTrack, echo, waveEnv);
                wi.getTrackQueue().incoming(msg);
            }
        }

        if (result && !tail.trim().equals("")) {
            Wave newWave = new Wave(tail, waveEnv);
            waveQueue.incomingFront(newWave);
        }
        waveEnv.dump();
        //Utilities.WPPrint("Result: " + result);
        Utilities.WPPrint("Greater Equal has done.");
    }

    private Vector getChild(ASTGreaterEqual grEquals, int intPos) {
        SimpleNode child = (SimpleNode) grEquals.jjtGetChild(intPos);
        Vector v = new Vector();
        Object obj = new Object();
        if (child instanceof ASTFrontalVar) {
            obj = waveEnv.getFrontalTable().get(child.getString());
        //Utilities.WPPrint("OBJ VALUE: " + obj);
        } else if (child instanceof ASTNodalVar) {
            Hashtable<String, Vector> nodalTable =
                    kn.getKNNode(waveEnv.getCONTENT()).getNodalTable(waveEnv.getColor());
            obj = nodalTable.get(child.getString());
        } else {
            obj = child.getString();
        }
        if (obj instanceof Collection) {
            v.addAll((Collection) obj);
        } else {
            v.add(obj);
        }
        return v;
    }

    public Vector getLeftChild(ASTGreaterEqual grEquals) {
        return getChild(grEquals, 0);
    }

    public Vector getRightChild(ASTGreaterEqual grEquals) {
        return getChild(grEquals, 1);
    }
}
